package cn.just.student_mall.service;

import cn.just.student_mall.entity.User;
import cn.just.student_mall.mapper.UserMapper;
import cn.just.student_mall.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @Author wujiaming
 * @Description TODO
 * @Date 2021-03-24 14:34
 * @Version 1.0
 */

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    /**
     * 用户注册
     * @param user
     * @throws UsernameDuplicateException
     * @throws InsertException
     */
    public void regist(User user) throws UsernameDuplicateException,
            InsertException {
        //获取用户名 判断用户是否已占用
        System.out.println(user);
        User dbUser = userMapper.findByUserName(user.getUsername());
        if(dbUser != null){
            //手动抛出异常对象
            throw new UsernameDuplicateException();
        }

        //加密密码
        //唯一通识码 salt
        String salt = UUID.randomUUID().toString();
        user.setSalt(salt);
        String md5Password =getMd5Password(user.getPassword(),salt);
        user.setPassword(md5Password);
        //0-未删除
        user.setIsDelete(0);
        //创建人
        user.setCreatedUser(user.getUsername());
        //获取当前时间
        Date now = new Date();
        user.setCreatedTime(now);
        //修改人
        user.setModifiedUser(user.getUsername());
        //修改时间
        user.setModifiedTime(now);

        //执行新增
        int row = userMapper.addUser(user);
        //判断受影响的行数是否为1
        if(row != 1){
            throw  new InsertException();
        }
    }

    /**
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录后的用户信息
     */
    public User login(String username,String password) throws UserNotFoundException,
            PasswordNotMatchException{

        //根据用户查询用户信息 查询结果是null 抛出UserNotFoundException
        //is_delete结果是1 抛出UserNotFoundException
        User dbUser = userMapper.findByUserName(username);
        //排除空指针的情况
        if(dbUser == null){
            throw new UserNotFoundException();
        }
        Integer isDelete = dbUser.getIsDelete();
        if(isDelete == 1){
            throw new UserNotFoundException();
        }
        //取出用户salt值，和请求参数password 执行加密 得到密文
        //判断以上的密文和用户数据的密文是否一致，如果不相同抛出PasswordNotMatchException
        String salt = dbUser.getSalt();
        String md5Password = getMd5Password(password,salt);
        if(!md5Password.equals(dbUser.getPassword())){
            throw new PasswordNotMatchException();
        }
        //返回查询结果
        return dbUser;
    }

    /**
	 * 执行密码加密，获取加密后的密码
	 * @param password 原始密码
	 * @param salt 盐值
	 * @return 加密后的密码
	 */
	private String getMd5Password(
			String password, String salt) {
		// 加密规则：
		// 1. 使用“盐 + 密码 + 盐”作为原文
		// 2. 三重加密
		System.err.println("\t加密-原始密码：" + password);
		System.err.println("\t加密-盐值：" + salt);
		for (int i = 0; i < 3; i++) {
			password = DigestUtils.md5DigestAsHex(
					(salt + password + salt).getBytes());
		}
		System.err.println("\t加密-密文：" + password);
		return password;
	}

    /**
     * 跟换头像
     * @param uid
     * @param username
     * @param avatar 上传得到的头像文件路径
     * @throws UpdateException
     */
	public void changeAvatar(Integer uid,String username,
                             String avatar) throws UpdateException{
        Integer row = userMapper.updateAvatarByUid(uid, avatar, username, new Date());
        //判断受影响的行数
        if(row !=1){
            throw new UpdateException();
        }
	}


}
